<template>
	<div class="setting">
		<div class="header-bar" v-show="false">
			<div class="iconfont" @click="goBack">&#xe624;</div>
			代开
		</div>
		<div class="warrp" id="avatar-con">			
			<div class="avatar">
				<div class="upload_imgs" id="uploadImgs" @click.stop="autoClick(0)">
					<img class="avatar-img" :src="avatar"/>							
					<input type="file" accept="image/jpg,type/face" @change="onFileChange0" style="display:none;" id="upfile0">
				</div>		
				<div class="desc">点击修改店铺头像</div>
			</div>
			<div class="bg-img">
				<img :src="avatar" height="100%" width="100%" alt="" />				
			</div>
			<div class="drop"></div>
		</div>
		<div class="content">
			<group label-width="5.5em" label-margin-right="2em" >
				<x-input :disabled="true" title="商店名称" v-model="shopName"></x-input>
				<popup-picker value-text-align="left" title="服务范围" :data="storeCates" v-model="activityType"></popup-picker>
				<popup-picker value-text-align="left" title="商圈" v-show="areaList.length" :data="areaArr" v-model="area"></popup-picker>
		    	<x-input title="详细地址" type="text" v-model="detailAddress" placeholder="请输入详细地址"></x-input>	
		    	 <cell title="门店实景图(5张)" style="white-space: nowrap;"></cell>
		    	<div class="gallery">
					<div class="upload_img arr-up" v-for="(item,index) in imgList" v-if="imgList.length">
						<img class="showImg2 arr-img previewer-demo-img"  :src="item.src" height="100%" width="100%" @click="show(index)"/>
					</div>
					<div v-transfer-dom>
					    <previewer :list="imgList" ref="previewer" :options="options" @on-index-change="logIndexChange"></previewer>
					</div>
					<div class="upload_img" id="uploadImgs" @click.stop="autoClick(2)" v-if="imgList.length < 5">
						<div class="desc iconfont" style="text-align: center;line-height: 1.6rem;font-size: .5rem;color: #ccc;">&#xe601;</div>	
						<input type="file" multiple="multiple" style="" @change="onFileChangeList"  id="upfile1">
					</div>
			    </div>
		    	<x-textarea title="商店介绍" :max="200" v-model="shopIntroduce"></x-textarea>
		    </group>

	    	<div class="agreement">点击下一步代表您同意 <span class="point">&lt;&lt;阿宝商户入住协议&gt;&gt;</span></div>
	    	<div class="btn" @click="submitForm">立即创建</div>
	    	<div class="bottom-bar"></div>
		</div>
	    <div v-transfer-dom>
	      <x-dialog v-model="dshow" class="dialog-demo">
	        <div class="img-box" style="padding: .4rem;">
	          	<h3 class="title">创建成功</h3>
	          	<x-button @click.native="continueCreate" :mini="true" type="warn">继续创建</x-button>
	          	<x-button @click.native="goHome" :mini="true" type="warn">返回首页</x-button>
	        </div>	        
	        <div @click="dshow=false">
	          <span class="vux-close"></span>
	        </div>
	      </x-dialog>
	    </div>
	</div>
</template>

<script>
	import { Previewer, TransferDom } from 'vux'
	import { getUrlParam }  from '@/assets/js/getUrlParam'
	import { iosOrAndr }  from '@/assets/js/isIos'
	import { setCookie, getCookie, removeCookie, clearCookie } from '@/assets/js/cookie'
	import { PopupRadio , Spinner, XDialog , GroupTitle, Group, Cell, XInput, Selector, PopupPicker, XButton, XNumber, ChinaAddressV4Data, XAddress, XTextarea, XSwitch } from 'vux'
	export default{
		name : "proxyOpenShop",
		data(){
			return{
				dshow     : false,
				avatar   : require('../../assets/images/groups/upload.jpg'),
				isWeChat : true,
				shopName :'',		//商店名称
				activityType : ['请选择服务范围'],
				area         : ['请选择商圈'],
				activityOptions:['1','2','3'],
				detailAddress : '', //详细地址
				shopIntroduce : '',//商店介绍
				lenImg0	: 0,
				imgU0   : '',
				okUrl0   : '',
				storeInfo    : {},	//商业的商店信息
				storeCate    : {},	//服务范围
				sysType   	 : '',
				comefrom     : '',
				shopid       : '',
				areaList     : [],	//区县List
				areaId       : '', //区县ID
				imgList      : [],
				lenImg       : 0,
				options: {
			        getThumbBoundsFn (index) {			        
			          let thumbnail = document.querySelectorAll('.previewer-demo-img')[index]			        
			          let pageYScroll = window.pageYOffset || document.documentElement.scrollTop	
			          let rect = thumbnail.getBoundingClientRect()			          
			          return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
			        }
		        },
				officiaImgs : [],
				privonce    : '',
				city        : '',
				country		: '',
			}
		},
		mounted(){
			document.title = '代开'
			//调用获取服务范围的方法
			this.sysType = iosOrAndr()
			//this.fuid = getUrlParam('fuid') || ''
			this.isWeixin()
			window.cameraResult = this.cameraResult
			this.getStoreCate()
			//获取上个页面的数据		
			this.branchName = this.$route.query.branch || ''
			this.shopName   = this.$route.query.name
			let areas= this.$route.query.area
			this.citys = areas.split(';')
			console.log(this.city)
				//this.getStoreInfo()
			this.getTradingArea()

		},
		directives: {
		   TransferDom
		},
		methods:{
			show(index){
				this.$refs.previewer.show(index)
			},
			logIndexChange(){
				
			},
			//返回首页
			goHome(){
				this.$router.push('/home')
			},
			//继续创建
			continueCreate(){
				this.$router.push('/createShop')
			},
			//获取市区
			getTradingArea(){
				let cityId = ''
				if(this.citys[0] === "110000" || this.citys[0] === "120000" || this.citys[0] === "310000" ||this.citys[0] === "500000"){
					cityId = this.citys[0]
				}else{
					cityId = this.citys[1]
				}
				let info = {
					userinfo : this.getParams(),
					id_area  : cityId
				}
				this.$axiosGet('/api/maker/storeCityArea',{
					data : JSON.stringify(info)	
				}).then( res => {
					if(res.code === 200){
						this.areaList = res.data
					}
				})
			},
			//返回上一页
			goBack(){
				this.$router.go(-1)
			},
			//获取店铺信息
//			getStoreInfo(){
//				let info = {
//					userinfo : this.getParams(),
//					shop_id  : this.shopid
//				}
//				this.$axiosGet('/api/store/getStoreInfo',{
//					data : JSON.stringify(info)
//				}).then( res => {
//					if(res.code === 200){
//						this.storeInfo = res.data
//						this.avatar 	   = this.storeInfo.frontImg
//						this.shopName 	   = this.storeInfo.name
//						this.detailAddress = this.storeInfo.address
//						this.areaList      = this.storeInfo.area_arr
//					}
//					if(res.code === 404){
//						this.$vux.toast.text('店铺不存在')
//					}
//				})
//			},
			//提交表单数据
			submitForm(){
				
				let catId  = ''
				for(let item in this.storeCate){
					if(this.activityType[0] === this.storeCate[item]){
						catId = item
					}
				}
				this.areaList.forEach( item => {
					if(item.name === this.area[0]){
						this.sq_id   = item.sq_id
						this.sq_pid  = item.sq_pid
						this.sq_name = item.name
						console.log(this.sq_name )
					}
				})
				if(this.citys[0] === "110000" || this.citys[0] === "120000" || this.citys[0] === "310000" ||this.citys[0] === "500000"){
					this.city 	 = this.citys[0]
					this.country  = this.citys[1]
				}else{
					this.privonce = this.citys[0]
					this.city 	 = this.citys[1]
					this.country  = this.citys[2]
				} 
				let shopInfo = {
					userinfo     : this.getParams(),
					frontImg	 : this.okUrl0,
					name    	 : this.shopName,
					branchName   : this.branchName,					
					province	 : this.privonce || '',
					city	     : this.city,
					country      : this.country,
					cateName 	 : this.activityType,
					cateId       : catId,
					sq_id        : this.sq_id || '',
					sq_pid       : this.sq_pid || '',
					sq_name      : this.sq_name || '',
					address		 : this.detailAddress,					
					introduction : this.shopIntroduce,
					officialFrontImgs : this.officiaImgs,
					comefrom     : this.comefrom
				}
				console.log(shopInfo)
//				if(this.sysType === 'ios' && this.isWeChat){
//					shopInfo.storeAvatar 	 = this.imgU0
//					shopInfo.scard_1 		 = this.imgU1
//					shopInfo.scard_2 		 = this.imgU2
//					shopInfo.licencePath	 = this.imgU3
//					shopInfo.foodLicencePath = this.imgU4
//				}
				let result = this.validateForm()
				if(result.status){
					//存在fuid
					//if(this.fuid){
						//shopInfo.fuid = this.fuid
						this.$axiosPost('/api/maker/creatStore',{
							data : JSON.stringify(shopInfo)
						}).then(res => {
							if(res.code === 200){
								this.dshow = true
								//setCookie('claimSt',this.storeInfo.id)
								//this.$router.replace({path:'/examine',query:{status:0,fromin:'setting'}})
							}else{
								this.$vux.toast.text('创建失败','top')
							}
						})
					//}
					//不存在fuid
					//if(!this.fuid || this.fuid == 0){
						//sessionStorage.setItem('shopInfo',JSON.stringify(shopInfo))
						//this.$router.replace({path:'/queryServerNum',query:{status:this.storeInfo.id,fromin:'setting'}})
					//}
				}else{
					this.$vux.toast.text(result.msg, 'top')
				}
			},
			

			//获取URL的参数
			getParams(){
				let userinfo = {
					uid   : getUrlParam('uid')   || getCookie('uid'),
					token : getUrlParam('token') || getCookie('token')
				}
				return userinfo
			},

			//获取服务范围
			getStoreCate(){
				let info = {
					userinfo : this.getParams()
				}
				this.$axiosPost('/api/store/getStoreCate',{
					data : JSON.stringify(info)
				}).then( res => {
					if(res){
						this.storeCate = res
					}else{
						this.$vux.toast.text('数据加载失败','top')
					}
				})
			},
			//ios返回来的图片
			cameraResult(type,result){	
				if(type && result){
					if(type === 'face'){
						this.avatar = result
						this.okUrl0 = result
					}
				}
			},
			//多图上传
			onFileChangeList($event){
				let _this = this
				this.lenImg += Number($event.target.files.length)
				if(this.lenImg > 5){
					this.lenImg = 0
					this.$vux.toast.text('最多上传5张','middle')
					return
				}
				let fileArr = $event.target.files
				for(let i = 0;i < fileArr.length;i++){
				 	let file = fileArr[i]
				 	let reader = new FileReader()
				 	reader.onload = function(e){
				 		_this.$vux.loading.show({text:'上传中'})
				 		let params = _this.getParams()
				 		let url = `/utils/files/uploadbase64.json?uid=${params.uid}&token=${params.token}`
				 		_this.$axiosPost( url,{
				 			upload: e.target.result
				 		},true).then( res => {
				 			_this.$vux.loading.hide()
				 			if(res.code === 200){
				 				_this.imgList.push({
				 					msrc : res.data.fullpath,
				 					src  : res.data.fullpath
				 				})
				 				_this.officiaImgs.push(res.data.path)
				 			}
				 		})
				 	}
				 	 reader.readAsDataURL(file);
				 }
			},
			//点击代理
			autoClick(index) {
				if(!this.isWeChat){
					if(index === 0){
						let type = [ 'camera','album']
						this.getWxUpId("avatar","okUrl"+index,type,1)
					}else{
						let type = ['camera','album']
						this.getWxUpId("imgList","officiaImgs",type,5)
					}
					return
				}
				if(this.sysType === 'ios' && this.comefrom === 1 && index === 0){
					this.iosUpload(index)
					return
				}
				if(index === 0){
					document.getElementById("upfile0").click();
				}else if(index === 2){
					//document.getElementById("upfile1").click();					
				}
				
			},
			//调用微信的图片上传
			getWxUpId(name,okName,type,count){
				let _this = this
				this.$wxUploadImg({count: count,sourceType:type},
				function(localId){
					if(count === 1){
						_this[name] = localId;
					}else{
						_this[name].push({
							src  : localId,
							msrc : localId
						})
					}
				},function(data,localId){
					if(count === 1){
						_this[okName] = data.url;//data.fullurl;
					}else{
						_this[okName].push(data.url)
					}
					
				});
			},
			//告诉IOS调用相机
			iosUpload(index){
				if(index === 0){
					window.webkit.messageHandlers.MofingWKWebview.postMessage({type:'face'})
				}
			},
			//上传文件
			onFileChange0($event,index) {		
				let self = this;
				this.$vux.loading.show({text:'上传中'})
				this.lenImg0 = $event.target.files.length;
				if(this.lenImg0 === 0) {
					return;
				}		
				let fileArr = $event.target.files;
				var file=fileArr[0];
				var reader = new FileReader();				                       		                       
		            reader.onload = function (e) {	
		            	self.imgU0 = e.target.result;
				        	self.$axiosPostno('/utils/files/uploadbase64.json',{
				    			upload : self.imgU0
					        }).then(res=>{
					        	self.$vux.loading.hide()
					        	if(res.code === 200){
					        		self.okUrl0 = res.data.path
					        		self.avatar = res.data.fullpath
					        	}
					        })
			        }
		            reader.readAsDataURL(file);
			},
			//表单验证
			validateForm(){
				let result = {
					status : false,
					msg    : ''
				}
				if(!this.okUrl0){
					result.msg = '请上传头像'
					return result
				}
				if(!this.shopName){
					result.msg = '请填写商店名称'
					return result
				}
				if(this.activityType[0] === '请选择服务范围'){
					result.msg = '请选择服务范围'
					return result
				}
				if(this.area[0] === '请选择区县'){
					result.msg = '请选择区县'
					return result
				}
				if(!this.detailAddress){
					result.msg = '请填写详细地址'
					return result
				}
//				if(!this.userName){
//					result.msg = '请填写您的姓名'
//					return result
//				}
//				if(!this.result){
//					result.msg = '请输入正确的身份证号'
//					return result
//				}
//				if(!this.imgU1){
//					result.msg = '请上传您本人身份证照正面'
//					return result
//				}
//				if(!this.imgU2){
//					result.msg = '请上传您本人身份证照反面'
//					return result
//				}
//				if(!this.imgU3){
//					result.msg = '请上传您的营业执照'
//					return result
//				}
//				if(!this.phone){
//					result.msg = '请输入11位手机号码'
//					return result
//				}
//				if(!this.validateCode){
//					result.msg = '请输入验证码'
//					return result
//				}
//				if(this.isTake){
//					if(!this.imgU4){
//						result.msg = '请上传您的餐饮许可证'
//						return result
//					}
//				}
				result.status = true
				return result
			},
			isWeixin(){
				let agent = navigator.userAgent.toLowerCase();
			    if (agent.match(/MicroMessenger/i) == "micromessenger") {
			       	this.isWeChat = false
			       	this.$wxConfig()
			       	this.comefrom  = 2
			       	document.title = '店铺认领'
			       	document.getElementById('avatar-con').style.margin = 0
			    } else {
			    	this.comefrom  = 1
			        this.isWeChat = true
			    }
			},
		},
		watch:{
			sq_name(){

			}
		},
		computed:{
			storeCates(){
				let cates = []
				if(this.storeCate){
					for(let item in this.storeCate){
						cates.push(this.storeCate[item])
					}
					return [cates]
				}
			},
			areaArr(){
				let arr = []
				if(this.areaList){
					this.areaList.forEach( item => {
						arr.push(item.name)
					})
					return [arr]
				}
			}
		},
		components:{
			Group,
	        GroupTitle,
	        Cell,
	        XInput,
	        Selector,
	        PopupPicker,
	        XAddress,
	        XNumber,
	        XTextarea,
	        XSwitch,
	        PopupRadio,
	        XButton,
	        Spinner,
	        Previewer,
	        XDialog
		}
	}
</script>

<style lang="less" scoped>
	@import '~vux/src/styles/1px.less';
	.setting /deep/ .weui-cells{
		margin-top: 0;
	}
	.setting /deep/ .weui-label{
		white-space: nowrap;
	}
	.setting /deep/ .weui-btn{	
		background:#ff1351;
	}
	.setting /deep/ .weui-switch{
		background:#ff1351 ;
	}
	.setting /deep/ .weui-switch:checked{
		border-color:#ff1351;
	}
	.setting /deep/ .weui-input{
		font-size: .24rem;
	}

	.setting /deep/ .vux-popup-picker-value{
		font-size: .24rem;
	}
		.dialog-demo {
		  .weui-dialog{
		    border-radius: 8px;
		    padding-bottom: 8px;
		  }
		  .title{
		  	line-height: .8rem;
		  }
		  .dialog-title {
		    line-height: 30px;
		    color: #666;
		  }
		  .img-box {
		    overflow: hidden;
		  }
		  .vux-close {
		    margin-top: 8px;
		    margin-bottom: 8px;
		  }
		}

	.setting{
		text-align: left;
		background: #fff;
		.header-bar{
			position:fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 199;
			height:1.44rem;
			line-height:2rem;
			text-align:center;
			font-size:.34rem;
			background:#f7f7f8;
			color:#000;
			.iconfont{
				position: absolute;
				left: 0;
				top: .54rem;
				height: .9rem;
				line-height: .9rem;
				padding: 0 .2rem;
			}
		}
		.warrp{
			position: relative;
			overflow:hidden;
			margin-top: 0rem;
			width:100%;
			height: 4.6rem;
			.avatar{
				position: absolute;
				left: 50%;
				top: 50%;
				margin-top: -1rem;
				margin-left: -1rem;
				z-index: 10;
				height: 2rem;
				width: 2rem;
				border: 1px solid #fff;
				border-radius: 50%;
				.upload_imgs{
					width: 100%;	
					height: 100%;							
					display: flex;
					flex-flow: wrap;				
					align-items: center;	
					position: relative;
					img{
						height: 100%;
						width: 100%;
						border-radius: 50%;
					}	
				}
				.desc{
					width: 100%;
					line-height: .5rem;
					text-align: center;
					z-index: 100;
					color: #fff;
					font-size: .2rem;
				}
			}
			.bg-img{
				z-index: -100;
				width: 100%;
				height: 100%;
				filter: blur(.2rem);
			}	
			.drop{
				position: absolute;
				left: 0;
				top: 0;
				z-index: -50;
				height: 100%;
				width: 100%;
				background: rgba(255,255,255,.2);
			}		
		}
		.agreement{
			padding: 0 .3rem;
			line-height: 1rem;
			.point{
				color: #d49931;
			}
		}
		.vali-code{
			width: 1.4rem;
			padding-left: .2rem;
			text-align: center;
			font-size: .24rem;
			color: #ff1351;
		}
		.id-cart{
			position: relative;
			display: flex;
			padding: .2rem .3rem;
			height: .1.2rem;	
			line-height: 1.2rem;
			font-size: .34rem;	
			.left{
				height: .88rem;
				white-space: nowrap;
				width: 1.88rem;
				height: 100%;				
				margin-right: .68rem;				
			}
		}
		.gallery{
			overflow: hidden;
			padding:.1rem .3rem;
			.upload_img{
				position: relative;
				float: left;
				margin-right: .1rem;
				margin-bottom: .1rem;
				height: 1.6rem;
				width: 1.6rem;
				border: 1px #ccc solid;
				pointer-events: auto;
				#upfile1{
					position: absolute;
					left: 0;
					top: 0;
					height: 1.6rem;
					width: 1.6rem;
					opacity: 0;
				}
			}
		}
		.btn{
			margin: 0 auto;
			width: 90%;
			height: .8rem;
			line-height: .8rem;
			text-align: center;
			background: #ff1351;
			color: #fff;
			border-radius: .1rem;
		}
		.bottom-bar{
			height: .3rem;
			background: #fff;
		}
	}
</style>